//
//  ViewController.m
//  Negative Binomial
//
//  Created by linchu on 2019/3/1.
//  Copyright © 2019 linchu. All rights reserved.
//

#import "ViewController.h"
#import "AlertHelper.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *nTf;
@property (weak, nonatomic) IBOutlet UITextField *rTf;
@property (weak, nonatomic) IBOutlet UITextField *pTf;
@property (weak, nonatomic) IBOutlet UILabel *resultLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)calAction:(id)sender {
    
    
    if([_nTf.text isEqualToString:@""] || [_rTf.text isEqualToString:@""] || [_pTf.text isEqualToString:@""] )
    {
        return;
    }
    
    if (_pTf.text.floatValue >1) {
        
        
        [AlertHelper showAlertWithtitle:@"Warning" content:@"p may between 0 and 1."];
        
        return;
    }
    
    if (_rTf.text.floatValue > _nTf.text.floatValue) {
        
        [AlertHelper showAlertWithtitle:@"Warning" content:@"r may lower than n."];

        return;
    }
    
    CGFloat n = _nTf.text.floatValue;
    CGFloat r = _rTf.text.floatValue;
    CGFloat p = _pTf.text.floatValue;
    
    CGFloat a = n -1;
    
    CGFloat b = r -1;
    
    CGFloat z = 1;
    
    for (int i = a; i>=1; i--) {
        
        z = z*i;
    }
    
    CGFloat t = 1;
    for (int i = b; i>=1; i--) {
        
        t = t* i;
    }
    
    CGFloat x = a-b;
    CGFloat s = 1;
    
    for (int i = x; i>=1; i--) {
        s = s*i;
    }
    
    CGFloat c = z/s;
    
    CGFloat d= c/t;
    CGFloat e = pow(p, r);
    CGFloat f = 1 -p;
    CGFloat g = n-r;
    CGFloat h = pow(f, g);
    CGFloat res = d*e*h;
    
    CGFloat result = round((res) * 100000)/100000;
    
    self.resultLabel.text = [NSString stringWithFormat:@"%f",result];
    
    
}


@end
